package net.ddyule.www.ddyule;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.Toast;

import com.iflytek.cloud.SpeechUtility;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.smtt.sdk.QbSdk;

import net.ddyule.www.ddyule.util.X5WebView;

import java.util.Timer;
import java.util.TimerTask;

import static android.view.KeyEvent.KEYCODE_BACK;

public class MainActivity extends AppCompatActivity{
    static ImageView mImageView;
    static X5WebView webView;
    static public Activity sContent;
    private boolean isBuglyInit =false;
    static  public AndroidToJs androidjs;
    static public  PowerManager.WakeLock wakeLock;
   // public static TextToSpeech tts;
    Timer timer;
    TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        ///保持屏幕常亮
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        sContent = this;



        mImageView = findViewById(R.id.imageView);
        new Handler().postDelayed(new Runnable(){
            public void run() {
                try {
//                    Intent intent = new Intent(MainActivity.this, MyService.class);
//                    startService(intent);

                    initX5Engine();
                }catch (Exception E){
                    Toast.makeText(MainActivity.this, "initX5Engine exception="+E.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }, 500);

    }

    protected void onStart(){


        super.onStart();

//            Intent intent = new Intent(this, download_info.class);
//            startActivity(intent);
    }

    protected void onDestroy()
    {
        System.exit(0);
        super.onDestroy();
    }

    protected void onResume()
    {
        super.onResume();
//        if(webView != null) {
//            webView.onResume();
//            webView.resumeTimers();
//        }
//
//        if(androidjs != null)
//            androidjs.onReusme();
        if(isBuglyInit)
            Beta.checkUpgrade(false,true);
    }

    protected void onPause()
    {
        super.onPause();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && webView != null) {
//            webView.onPause(); // 暂停网页中正在播放的视频
//        }
//        if(webView != null) {
//            webView.pauseTimers();
//        }
//
//        if(androidjs != null)
//            androidjs.onPause();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KEYCODE_BACK) ) {
            if(webView.canGoBack())
            webView.goBack();
            else
                this.finish();
            return true;
        }
       return super.onKeyDown(keyCode, event);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */

    private void initX5Engine(){
//        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
//
//            @Override
//            public void onViewInitFinished(boolean arg0) {
//                // TODO Auto-generated method stub
//                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
//                Log.d("app", " onViewInitFinished is " + arg0);
//
//              //  Toast.makeText(MainActivity.this, "初始化结果:"+arg0, Toast.LENGTH_SHORT).show();
//
//            }
//
//            @Override
//            public void onCoreInitFinished() {
//                // TODO Auto-generated method stub
//               // Toast.makeText(MainActivity.this, "x5 core init finish", Toast.LENGTH_SHORT).show();
//            }
//        };
        //x5内核初始化接口
       // QbSdk.initX5Environment(getApplicationContext(),  cb);
        //Toast.makeText(this, "初始化X5开始", Toast.LENGTH_SHORT).show();
        //讯飞初始化
        SpeechUtility.createUtility(sContent, "appid=" + getString(R.string.app_id));
        initX5WebView();
        webView.loadUrl(Constants.Webview_URL);

       // initBugly();
    }

    private void initX5WebView()
    {
        webView = findViewById(R.id.webview);

        String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();   //缓存数据的存储地址
        webView.getSettings().setAppCachePath(appCacheDir);

        androidjs = new AndroidToJs();
        webView.addJavascriptInterface(androidjs, "app");
        if (NetWorkUtil.hasNetwork(getApplicationContext()))
            webView.getSettings().setCacheMode(com.tencent.smtt.sdk.WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
            else
            webView.getSettings().setCacheMode(com.tencent.smtt.sdk.WebSettings.LOAD_CACHE_ELSE_NETWORK);

//            webView.getSettings().setCacheMode(com.tencent.smtt.sdk.WebSettings.LOAD_NO_CACHE);



    }

    private void initBugly()
    {
        Beta.initDelay = 3000;
        Bugly.init(getApplicationContext(), Constants.Bugly_ID, false);
        isBuglyInit = true;
    }

    static public void onPageFinish()
    {
        mImageView.setVisibility(View.GONE);
    }

    public static void makeScreenOn() {
        PowerManager pm = (PowerManager) MainActivity.sContent.getSystemService(POWER_SERVICE);// init powerManager
        PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|
                PowerManager.SCREEN_DIM_WAKE_LOCK,"target"); // this target for tell OS which app
        mWakelock.acquire();

        // 键盘锁管理器对象
        KeyguardManager km = (KeyguardManager) MainActivity.sContent.getSystemService(Context.KEYGUARD_SERVICE);
        // 这里参数”kale”作为调试时LogCat中的Tag
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("kale");
        if (km.inKeyguardRestrictedInputMode()) {
            // 解锁键盘
            kl.disableKeyguard();
        }

    }

}
